package com.oceansoft.mobile.econsole.vehicle.service.imp;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.axis.encoding.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


//import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.image.ImageUtil;
import com.oceansoft.mobile.econsole.modules.api.entity.DriverInfo;
import com.oceansoft.mobile.econsole.modules.api.entity.DriverInfoApi;
import com.oceansoft.mobile.econsole.modules.api.entity.VehicleInfo;
import com.oceansoft.mobile.econsole.modules.api.entity.ViolationDriver;
import com.oceansoft.mobile.econsole.modules.api.entity.ViolationInfo;
import com.oceansoft.mobile.econsole.modules.api.entity.ViolationPhoto;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.vehicle.persistence.VehicleMapper;
import com.oceansoft.mobile.econsole.vehicle.service.IVehicleService;
import com.oceansoft.mobile.econsole.vehicle.service.TrafficVehicleService;

@Service
public class VehicleServiceImp extends CacheBaseService implements IVehicleService{

	@Resource
	private VehicleMapper vehicleMapper;
	private TrafficVehicleService tvs;
	
	
	private String savePhotoToDir(byte[] photoContent,String biz){
		ByteArrayInputStream input = null;
		FileOutputStream output = null;
		//文件路径 violation/20150319/(违法记录序号)/照片名.jpg
		String picName = String.format("%s/%s/%s%s","violation",biz, DigestUtils.md5DigestAsHex(photoContent), ".jpg");
		//完整路径
		String picPath = String.format("%s/%s", configInfo.getFileUploadRootPath(), picName);
		File picFile = new File(picPath);
		File targetDir = FileUtils.makeDir(String.format("%s/%s/%s",configInfo.getFileUploadRootPath(),"violation",biz));
		//存储文件至文件系统
        if (targetDir !=null && !picFile.exists()) {
            try {
            	input = new ByteArrayInputStream(photoContent);
            	output = new FileOutputStream(picFile);
            	ImageUtil.resize(input, output, 800, "jpg");
                //FileUtils.createFile(new ByteArrayInputStream(photoContent), new File(picPath));
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
            	try {
            		if(input != null){
            			input.close();
            		}
            		if(output != null){
            			output.close();
            		}
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
        return configInfo.getFileDownloadUrl(picName);
	}
	
	@Override
	public Result queryVehicleViolation(VehicleInfo vehicleInfo) {
		tvs = TrafficVehicleService.getInstance();
		String key = "VEHICLE:"+vehicleInfo.getLicense()+vehicleInfo.getVin();
	    if (super.exists(key)) {
	        return new Result(Result.SUCC, super.getObject(key));
	    }
		if (!StringUtils.hasText(vehicleInfo.getLicense())) {
            return new Result(Result.FAILURE, "车牌号为空");
        }
		if (!StringUtils.hasText(vehicleInfo.getVin())) {
			return new Result(Result.FAILURE, "车架号为空");
		}
		vehicleInfo.setLicense(vehicleInfo.getLicense().toUpperCase().replace("0", "0").replace("I", "1"));
		vehicleInfo.setVin(vehicleInfo.getVin().toUpperCase().replace("0", "0").replace("I", "1"));
		VehicleInfo vi = vehicleMapper.loadVehicleCount(vehicleInfo);
		vehicleInfo.setVehicleType(vi.getVehicleType());
		String hphm = vehicleInfo.getLicense().substring(1);
		if(vi!=null){
			List<ViolationInfo> violations = new ArrayList<ViolationInfo>();
			try {
				String vioResults = tvs.getVioSurveil(vehicleInfo.getVehicleType(),hphm, vehicleInfo.getVin());
				JSONObject jobj=new JSONObject(vioResults);
				JSONArray array = jobj.getJSONArray("vioSurveil");
				for(int i=0;i<array.length();i++){
					JSONObject obj= (JSONObject)array.get(i);
					ViolationInfo violation = new ViolationInfo();
					String xh = (String)obj.get("XH");//序号					
					violation.setSn(xh);
					violation.setAddress((String)obj.get("WFDZ"));
					violation.setFins(Float.valueOf(obj.getInt("FKJE")));
					violation.setProcessFlag((String)obj.get("ZT"));
					violation.setPayFineFlag("未缴款");
					violation.setTime((String)obj.get("WFSJ"));
					violation.setProvider((String)obj.get("CJJGMC"));
					violation.setViolation((String)obj.get("WFXW"));
					String photoResult = tvs.getPhotoByXH(xh);
					JSONObject photoObj=new JSONObject(photoResult);
					String  photos = photoObj.getString("photo");
					byte[] photo = Base64.decode(photos);
					violation.setPhotos(new ArrayList<String>());
					String picPath = savePhotoToDir(photo,xh);
					violation.getPhotos().add(picPath);
					violations.add(violation);
				}
				super.cache(key,violations,1.0f);//缓存一天
			} catch (Exception e) {
				e.printStackTrace();
			}
			return  new Result(Result.SUCC,violations);
		}else{
			return new Result(Result.FAILURE,"没有查询到车辆信息");
		}
		/*if(vi!=null){
			List<ViolationInfo> violations = vehicleMapper.loadViolationInfo(vehicleInfo);
			if(violations == null || violations.isEmpty()){
				return new Result(Result.SUCC,"暂无违章记录");
			}
			for(ViolationInfo vio : violations){
				int clbj = 0,jkbj = 0;
                if(vio.getProcessFlag() != null){
                	clbj = Integer.parseInt(vio.getProcessFlag());
                }
                if(vio.getPayFineFlag() != null){
                	jkbj = Integer.parseInt(vio.getPayFineFlag());
                }
                //是否处理及交款标记
				vio.setProcessFlag(1 == clbj ? "已处理" : "未处理");
                vio.setPayFineFlag(1 == jkbj ? "已缴款" : "未缴款");				
				//违法车辆对应的图片
				ViolationPhoto photos = vehicleMapper.loadViolationPhoto(vio);
				if(photos != null){
					vio.setPhotos(new ArrayList<String>(3));
					//判断三张图片内容是否为空
		            if(photos.getPhotoContent1() != null && photos.getPhotoContent1().length != 0){
		            	String picPath = savePhotoToDir(photos.getPhotoContent1(),photos.getXh());
		            	vio.getPhotos().add(picPath);
		            }
		            if(photos.getPhotoContent2() != null && photos.getPhotoContent2().length != 0){
		            	String picPath = savePhotoToDir(photos.getPhotoContent2(),photos.getXh());
		            	vio.getPhotos().add(picPath);
		            }
		            if(photos.getPhotoContent3() != null && photos.getPhotoContent3().length != 0){
		            	String picPath = savePhotoToDir(photos.getPhotoContent3(),photos.getXh());
		            	vio.getPhotos().add(picPath);
		            }
				}
			}
		//	super.cache(key, violations, 1.0f);
			return  new Result(Result.SUCC,violations);
		}else{
			return new Result(Result.FAILURE,"没有查询到车辆信息");
		}*/
	}

	@Override
	public Result queryDriverViolation(DriverInfo driverInfo) {
		tvs = TrafficVehicleService.getInstance();
		String key = "DRIVER:"+driverInfo.getDrivingLicense()+driverInfo.getFn();
//		if (super.exists(key)) {
//	        return new Result(Result.SUCC, super.getObject(key));
//	    }
		if (!StringUtils.hasText(driverInfo.getDrivingLicense())) {
            return new Result(Result.FAILURE, "驾驶证号为空");
        }
		if (!StringUtils.hasText(driverInfo.getFn())) {
			return new Result(Result.FAILURE, "档案编号为空");
		}
		ViolationDriver vd = new ViolationDriver();
		try {
			String licenseResult = tvs.getLicenseInfo(driverInfo.getDrivingLicense(), driverInfo.getFn());
			JSONObject jobj=new JSONObject(licenseResult);
			JSONObject obj= jobj.getJSONObject("license");
			String date = obj.getString("YXQZ").substring(0, 10);
			vd.setYXQZ(date);
			vd.setXM(obj.getString("XM"));
			vd.setZJCX(obj.getString("ZJCX"));
			vd.setLJJF(String.valueOf(obj.getInt("LJJF")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Result(Result.SUCC,vd);
		/*List<ViolationDriver> rt = vehicleMapper.loadDriverViolation(driverInfo);
		if(rt == null ){
			return new Result(Result.SUCC,"未找到违法记录");
		}
		if(rt.isEmpty()){
			return new Result(Result.SUCC,"未找到违法记录");
		}
		//去掉时分秒
		String date = rt.get(0).getYXQZ().substring(0, 10);
		rt.get(0).setYXQZ(date);
		//super.cache(key, rt.get(0), 1.0f);
		return new Result(Result.SUCC,rt.get(0));*/
	}

	@Override
	public boolean validateAuth(String key,String appKey) {
		Map<String,String> param = new HashMap<String,String>();
		param.put("key", key);
		param.put("appkey", appKey);
		int rt = vehicleMapper.validateAuth(param);
		if(rt > 0){
			return true;
		}
		return false;
	}

	@Override
	public Result loadVehicleInfo(String sfzh) {
		JSONObject json = new JSONObject();
        json.put("SFZH", sfzh);
        json.put("CL", vehicleMapper.loadVehicleInfo(sfzh));
        json.put("JSZ", vehicleMapper.loadDriverInfo(sfzh));
//		System.out.println(json);
		return new Result(Result.SUCC,json.toString(),"success");
	}

	@Override
	public Result loadDriverInfo(String sfzh) {
		List<DriverInfoApi> driver = vehicleMapper.loadDriverInfo(sfzh);
		if(driver.isEmpty()){
			return new Result(Result.SUCC, "未查到驾驶证信息");
		}
		return new Result(Result.SUCC,driver);
	}

}
